package edu.suda.basic.mail.usingPOP3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;

public class RetriveMail
{
	public RetriveMail()
	{
		
	}
	public static String parsePlainPart(Multipart multipart) throws MessagingException, IOException
	{
		int count = multipart.getCount();
		for (int idx = 0; idx < count; idx++)
		{
			BodyPart bodyPart = multipart.getBodyPart(idx);
			if (bodyPart.isMimeType("text/plain"))
				return bodyPart.getContent().toString();
		}
		return null;
	}

	public static void parseMultipart(Multipart multipart) throws MessagingException, IOException
	{
		int count = multipart.getCount();
		System.out.println("count =  " + count);
		for (int idx = 0; idx < count; idx++)
		{
			BodyPart bodyPart = multipart.getBodyPart(idx);
			System.out.println(bodyPart.getContentType());
			if (bodyPart.isMimeType("text/plain"))
			{
				System.out.println("plain................." + bodyPart.getContent());
			}
			else
				if (bodyPart.isMimeType("text/html"))
				{
					System.out.println("html..................." + bodyPart.getContent());
				}
				else
					if (bodyPart.isMimeType("multipart   "))
						return;
		}
	}

	public static void copy(InputStream is, OutputStream os) throws IOException
	{
		byte[] bytes = new byte[1024];
		int len = 0;
		while ((len = is.read(bytes)) != -1)
		{
			os.write(bytes, 0, len);
		}
		if (os != null)
			os.close();
		if (is != null)
			is.close();
	}

	public static String getMailContent()throws MessagingException, IOException
	{
		
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "pop3");
		props.setProperty("mail.pop3.host", "pop3.sina.com");
		Session session = Session.getDefaultInstance(props);
		Store store = session.getStore("pop3");
		store.connect();
		Folder folder = store.getFolder("INBOX");
		folder.open(Folder.READ_WRITE);

		@SuppressWarnings("unused")
		int messageCount = folder.getMessageCount();
//		System.out.println(messageCount);
		Message[] messages = folder.getMessages();

		Message message = messages[messages.length - 1];
//		System.out.println(message.getSubject());
		
//		System.out.println("发送时间：" + message.getSentDate());
//		System.out.println("主题：" + message.getSubject());
//		System.out.println("内容：" + message.getContent());
		Object content = message.getContent();
		if (content instanceof MimeMultipart)
		{
			MimeMultipart multipart = (MimeMultipart) content;
			return parsePlainPart(multipart).toString();
		}

		folder.close(true);
		store.close();
		return null;
	}

}
